package com.sun.talk.utils

import com.qiniu.storage.UploadManager
import com.qiniu.common.Zone
import com.qiniu.storage.Configuration
import com.qiniu.common.QiniuException
import com.qiniu.storage.model.DefaultPutRet
import com.google.gson.Gson
import com.qiniu.util.Auth

object QiNiuUploadUtils {

    private const val QIUNIU_SERVER_URL = "http://pvprc27jq.bkt.clouddn.com/"
    private const val QIUNIU_AK = "u6L1MqOoS7tOWoWNCvdlbnzylqnc4PvCqzXjo3b2"
    private const val QIUNIU_SK = "WCN643oUGTOU-6B5vUhFxuhzI4ziJ9nss2bFl1H3"
    private const val QINIU_BUCKET = "sun_test"

    fun upload(localFilePath: String): String {
        //构造一个带指定Zone对象的配置类
        val cfg = Configuration(Zone.zone2())
        //...其他参数参考类注释
        val uploadManager = UploadManager(cfg)
        //...生成上传凭证，然后准备上传

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        val key: String? = null
        val auth = Auth.create(QIUNIU_AK, QIUNIU_SK)
        val upToken = auth.uploadToken(QINIU_BUCKET)
        return try {
            val response = uploadManager.put(localFilePath, key, upToken)
            //解析上传成功的结果
            val putRet = Gson().fromJson(response.bodyString(), DefaultPutRet::class.java)
            QIUNIU_SERVER_URL + putRet.key
        } catch (ex: QiniuException) {
            ""
        }
    }
}